package com.cmge.ad.interfaces.vo;

import java.lang.reflect.Field;
import java.util.regex.Pattern;

import com.cmge.ad.util.Constant;

public abstract class BaseReqMsg extends BaseMsg implements Validatable {
	
	/**
	 * 参数通用校验  适合内部没有其他对象的请求对象
	 */
	@Override
	public ValidateResult validate() throws Exception {
		ValidateResult resp = new ValidateResult();
		resp.setResult(Constant.DEAL_SUCCESS,"success","");
		Field[] fields = getClass().getDeclaredFields();
	    try {
			for(Field field : fields){
				if (!field.isAccessible()){
					field.setAccessible(true);  
				}  
				
				ParamValidate param = field.getAnnotation(ParamValidate.class);
			    if(param != null){
			       boolean require = param.require();  
			       if(require){
			    	  String regix = param.regex();
			    	  if(!Pattern.matches(regix,(CharSequence) field.get(this).toString())){
			    		  resp.setResult(Constant.PARAM_VALIDATE_ERROR, "validate fail! property name is "+field.getName(),field.get(this).toString());
			    		  return resp;
			    	  }
			       }else{
			    	   String regix = param.regex();
			    	   if(null != field.get(this) && !("").equals(field.get(this)) && !regix.equals("")){
			        	  if(!Pattern.matches(regix,(CharSequence) field.get(this).toString())){
			        		  resp.setResult(Constant.PARAM_VALIDATE_ERROR, "validate fail! property name is "+field.getName(),field.get(this).toString());
			        		  return resp;
			        	  }
			    	   }
			       }
			    }
			}
		} catch (Exception e) {
			resp.setResult(Constant.PARAM_VALIDATE_EXCEPTION, "validate exception!",e.getMessage());
		}
        return resp;
	}
}
